#!/usr/bin/python3
"""
Change OSTree configuration

Change the configuration for an OSTree repository.
Currently only the following values are supported:
  - `sysroot.readonly`
  - `sysroot.bootloader`

See `ostree.repo-config(5)` for more information.
"""

import os
import sys
import subprocess

import osbuild.api


SCHEMA = """
"additionalProperties": false,
"required": ["repo"],
"properties": {
  "repo": {
    "description": "Location of the OSTree repo.",
    "type": "string"
  },
  "config": {
    "type": "object",
    "additionalProperties": false,
    "description": "OSTree configuration groups",
    "properties": {
      "sysroot": {
        "type": "object",
        "additionalProperties": false,
        "description": "Options concerning the sysroot",
        "properties": {
          "bootloader": {
            "description": "Configure the bootloader that OSTree uses (use 'none' for BLS).",
            "type": "string",
            "enum": ["none", "auto", "grub2", "syslinux", "uboot", "zipl"]
          },
          "readonly": {
            "description": "Read only sysroot and boot",
            "type": "boolean"
          }
        }
      }
    }
  }
}
"""


def ostree(*args, _input=None, **kwargs):
    args = list(args) + [f'--{k}={v}' for k, v in kwargs.items()]
    print("ostree " + " ".join(args), file=sys.stderr)
    subprocess.run(["ostree"] + args,
                   encoding="utf-8",
                   stdout=sys.stderr,
                   input=_input,
                   check=True)


def main(tree, options):
    repo = os.path.join(tree, options["repo"].lstrip("/"))
    config = options["config"]

    for group, items in config.items():
        for key, value in items.items():
            name = f"{group}.{key}"
            ostree("config", "set", name, str(value),
                   repo=repo)


if __name__ == '__main__':
    stage_args = osbuild.api.arguments()
    r = main(stage_args["tree"],
             stage_args["options"])
    sys.exit(r)
